package com.zzsz.controller;


import com.alibaba.excel.EasyExcel;
import com.zzsz.common.core.controller.BaseController;
import com.zzsz.common.core.domain.AjaxResult;
import com.zzsz.domain.Product;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * --- 这有何难 ---
 * ƪ(˘⌣˘)ʃ
 *
 * @author 超级无敌张恒阳大王
 * @date 1/9/2025
 * @desc
 */
@Slf4j
@RestController
@RequestMapping("/warn")
public class WarnController extends BaseController {
	@Autowired
	private com.zzsz.service.WarnService warnService;

	/**
	 * 获取分类树形结构
	 */
	@GetMapping("/categoryTree")
	public AjaxResult getCategoryTree() {
		try {
			return AjaxResult.success(warnService.getCategoryTree());
		} catch (Exception e) {
			log.error("获取分类树形结构失败", e);
			return AjaxResult.error("获取分类树形结构失败: " + e.getMessage());
		}
	}

	/**
	 * 设置(变更)预警状态
	 */
	@PostMapping("/updateStatus")
	public AjaxResult setWarnStatus(@RequestBody Product product) {
		warnService.setWarnStatus(product);
		return AjaxResult.success();
	}

	/**
	 * 更新预警阈值
	 */
	@PostMapping("/updateThreshold")
	public AjaxResult updateThreshold(@RequestBody Product product) {
		warnService.updateThreshold(product);
		return AjaxResult.success();
	}

	/**
	 * 导出预警商品excel
	 */
	@GetMapping("/export-products")
	public void exportProducts(HttpServletResponse response) throws IOException {
		// 1. 设置响应头（文件名、格式）
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("UTF-8");
		String fileName = URLEncoder.encode("商品数据_" + LocalDate.now(), "UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

		// 2. 查询商品数据（复用预警系统的查询逻辑）
		List<Product> products = warnService.selectAllProduct(); // 需自行实现
		log.debug("products: {}", products);
		// 3. 转换为DTO并导出
		List<Product> exportData = products.stream().map(product -> {
			Product dto = new Product();
			dto.setProductId(product.getProductId());
			dto.setProductName(product.getProductName());
			dto.setSku(product.getSku());
			dto.setCategoryId(product.getCategoryId());
			dto.setQuantity(product.getQuantity());
			dto.setWarningThreshold(product.getWarningThreshold());
			dto.setAlertStatus(product.getAlertStatus());
			// ... 其他字段映射
			// dto.setAlertStatusDesc(product.getAlertStatus() == 1 ? "预警中" : "正常");
			return dto;
		}).collect(Collectors.toList());
		log.debug("exportData: {}", exportData);
		// // 4. EasyExcel写入响应流
		// EasyExcel.write(response.getOutputStream(), Product.class)
		// 		.sheet("商品列表")
		// 		.doWrite(exportData);
		// 4. 使用POI写入响应流（替换EasyExcel代码）
		Workbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("商品列表");

		// 创建表头
		Row headerRow = sheet.createRow(0);
		String[] headers = {"商品名称", "SKU", "分类ID", "数量", "预警阈值", "预警状态"};
		for (int i = 0; i < headers.length; i++) {
			headerRow.createCell(i).setCellValue(headers[i]);
		}

		// 填充数据行
		int rowNum = 1;
		for (Product product : exportData) {
			Row row = sheet.createRow(rowNum++);
			row.createCell(0).setCellValue(product.getProductName());
			row.createCell(1).setCellValue(product.getSku());
			row.createCell(2).setCellValue(product.getCategoryId());
			row.createCell(3).setCellValue(product.getQuantity());
			row.createCell(4).setCellValue(product.getWarningThreshold());
			row.createCell(5).setCellValue(product.getAlertStatus() == 1 ? "预警中" : "正常");
		}

		// 输出到响应流
		try (OutputStream os = response.getOutputStream()) {
			// 添加日志打印输出流信息
			log.info("Excel输出流准备就绪，即将写入数据: {}", exportData.size());
			if (!exportData.isEmpty()) {
				int printSize = Math.min(exportData.size(), 5);
				log.debug("前{}条导出数据: {}", printSize, exportData.subList(0, printSize));
			}
			workbook.write(os);
			log.info("Excel数据写入成功！");
		} finally {
			workbook.close();
			log.info("Excel工作簿已关闭");
		}

	}
}